package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.model.Board;
import com.example.forum.services.IBoradService;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.dao.BoardMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

@Api(tags = "板块管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/board")
public class BoardAdminController {

    @Resource
    private IBoradService boardService;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private BoardMapper boardMapper;

    /**
     * 获取所有板块列表
     * @param request HTTP请求
     * @return 板块列表
     */
    @ApiOperation("获取所有板块列表")
    @GetMapping("/list")
    public AppResult<List<Board>> getAllBoards(HttpServletRequest request) {
        List<Board> boards = boardService.getAllBoards();
        
        // 为每个板块获取实时文章数量
        if (boards != null && !boards.isEmpty()) {
            for (Board board : boards) {
                int actualCount = boardService.getActualArticleCount(board.getId());
                board.setArticleCount(actualCount);
            }
        }
        
        return AppResult.success(boards);
    }

    /**
     * 添加新板块
     * @param request HTTP请求
     * @param name 板块名称
     * @param sort 排序值（可选）
     * @return 操作结果
     */
    @ApiOperation("添加新板块")
    @PostMapping("/add")
    public AppResult addBoard(HttpServletRequest request,
                          @ApiParam("板块名称") @RequestParam("name") @NotBlank String name,
                          @ApiParam("排序值") @RequestParam(value = "sort", required = false) Integer sort) {
        Board board = new Board();
        board.setName(name);
        if (sort != null) {
            board.setSort(sort);
        }
        
        boardService.addBoard(board);
        return AppResult.success();
    }

    /**
     * 更新板块信息
     * @param request HTTP请求
     * @param boardId 板块ID
     * @param name 板块名称
     * @param sort 排序值
     * @return 操作结果
     */
    @ApiOperation("更新板块信息")
    @PostMapping("/update")
    public AppResult updateBoard(HttpServletRequest request,
                             @ApiParam("板块ID") @RequestParam("boardId") @NotNull Long boardId,
                             @ApiParam("板块名称") @RequestParam("name") @NotBlank String name,
                             @ApiParam("排序值") @RequestParam("sort") @NotNull Integer sort) {
        Board board = new Board();
        board.setId(boardId);
        board.setName(name);
        board.setSort(sort);
        
        boardService.updateBoard(board);
        return AppResult.success();
    }

    /**
     * 设置板块状态
     * @param request HTTP请求
     * @param boardId 板块ID
     * @param state 状态值（0正常，1禁用）
     * @return 操作结果
     */
    @ApiOperation("设置板块状态")
    @PostMapping("/state")
    public AppResult setBoardState(HttpServletRequest request,
                              @ApiParam("板块ID") @RequestParam("boardId") @NotNull Long boardId,
                              @ApiParam("状态值（0正常，1禁用）") @RequestParam("state") @NotNull Byte state) {
        boardService.updateBoardState(boardId, state);
        return AppResult.success();
    }

    /**
     * 删除板块
     * @param request HTTP请求
     * @param boardId 板块ID
     * @return 操作结果
     */
    @ApiOperation("删除板块")
    @PostMapping("/delete")
    public AppResult deleteBoard(HttpServletRequest request,
                             @ApiParam("板块ID") @RequestParam("boardId") @NotNull Long boardId) {
        try {
            boardService.deleteBoard(boardId);
            return AppResult.success();
        } catch (Exception e) {
            log.error("删除板块失败: {}", e.getMessage());
            return AppResult.failed(ResultCode.FAILED, e.getMessage());
        }
    }
    
    /**
     * 更新板块排序
     * @param request HTTP请求
     * @param boardId 板块ID
     * @param sort 排序值
     * @return 操作结果
     */
    @ApiOperation("更新板块排序")
    @PostMapping("/sort")
    public AppResult updateBoardSort(HttpServletRequest request,
                                @ApiParam("板块ID") @RequestParam("boardId") @NotNull Long boardId,
                                @ApiParam("排序值") @RequestParam("sort") @NotNull Integer sort) {
        boardService.updateBoardSort(boardId, sort);
        return AppResult.success();
    }

    /**
     * 检查和修复板块文章数
     * @return 修复结果
     */
    @ApiOperation("检查和修复板块文章数")
    @PostMapping("/fixArticleCounts")
    public AppResult<Map<String, Object>> fixArticleCounts() {
        log.info("开始检查和修复板块文章数...");
        
        // 获取所有未删除的板块
        List<Board> boards = boardService.getAllBoards();
        if (boards == null || boards.isEmpty()) {
            return AppResult.failed(ResultCode.ERROR_IS_NULL, "没有找到有效的板块");
        }
        
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> fixedBoards = new ArrayList<>();
        int totalFixed = 0;
        
        // 检查每个板块的文章数
        for (Board board : boards) {
            // 获取板块当前文章数
            int storedCount = board.getArticleCount() != null ? board.getArticleCount() : 0;
            
            try {
                // 修复文章计数并获取实际文章数
                int actualCount = boardService.fixArticleCount(board.getId());
                
                // 如果不一致，则记录修复信息
                if (storedCount != actualCount) {
                    Map<String, Object> fixInfo = new HashMap<>();
                    fixInfo.put("boardId", board.getId());
                    fixInfo.put("boardName", board.getName());
                    fixInfo.put("oldCount", storedCount);
                    fixInfo.put("newCount", actualCount);
                    fixInfo.put("status", "fixed");
                    
                    fixedBoards.add(fixInfo);
                    totalFixed++;
                }
            } catch (Exception e) {
                log.error("修复板块文章计数出错: boardId=" + board.getId(), e);
                
                Map<String, Object> fixInfo = new HashMap<>();
                fixInfo.put("boardId", board.getId());
                fixInfo.put("boardName", board.getName());
                fixInfo.put("oldCount", storedCount);
                fixInfo.put("status", "failed");
                fixInfo.put("error", e.getMessage());
                
                fixedBoards.add(fixInfo);
            }
        }
        
        result.put("totalChecked", boards.size());
        result.put("totalFixed", totalFixed);
        result.put("fixedBoards", fixedBoards);
        
        log.info("板块文章数检查和修复完成，共检查{}个板块，修复{}个板块", boards.size(), totalFixed);
        
        return AppResult.success(result);
    }

    /**
     * 修复特定板块的文章计数
     * @param id 板块ID
     * @return 修复结果
     */
    @ApiOperation("修复特定板块的文章计数")
    @PostMapping("/fixArticleCount")
    public AppResult<Map<String, Object>> fixArticleCount(@RequestParam("id") @NotNull Long id) {
        log.info("开始修复板块文章计数: boardId={}", id);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取板块信息
            Board board = boardService.selectById(id);
            if (board == null) {
                return AppResult.failed(ResultCode.ERROR_IS_NULL, "板块不存在");
            }
            
            // 获取当前文章计数
            int storedCount = board.getArticleCount() != null ? board.getArticleCount() : 0;
            
            // 修复文章计数
            int actualCount = boardService.fixArticleCount(id);
            
            result.put("boardId", id);
            result.put("boardName", board.getName());
            result.put("oldCount", storedCount);
            result.put("newCount", actualCount);
            result.put("fixed", storedCount != actualCount);
            
            log.info("板块文章计数修复完成: boardId={}, 原值={}, 新值={}", 
                    id, storedCount, actualCount);
            
            return AppResult.success(result);
        } catch (Exception e) {
            log.error("修复板块文章计数失败: boardId=" + id, e);
            return AppResult.failed(ResultCode.ERROR_SERVICES, "修复失败: " + e.getMessage());
        }
    }
} 